from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.generics import ListAPIView, CreateAPIView, UpdateAPIView, DestroyAPIView
from rest_framework.response import Response
from .serializers import AddressSerializer
from .models import Address


# Create your views here.

class AddressView(CreateAPIView, ListAPIView, UpdateAPIView):
    serializer_class = AddressSerializer

    # queryset = Address.objects.filter()

    def get_queryset(self):
        return Address.objects.filter(user=self.request.user, is_deleted=False)

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)

        return Response({'addresses': serializer.data, 'default_address_id': self.request.user.default_address_id})

    def delete(self, request, pk):
        user = self.get_object()
        user.is_deleted = True

        user.save()

        return Response()


class DefaultAddressView(APIView):
    def put(self, request, pk):
        user = self.request.user
        user.default_address_id = pk
        user.save()

        return Response()
